#include "TcpServer.hpp"
#include <memory>

static Response calculator(const Request &req)
{
    Response resp(0, 0);
    switch (req._op)
    {
    case '+':
        resp._result = req._x + req._y;
        break;
    case '-':
        resp._result = req._x - req._y;
        break;
    case '*':
        resp._result = req._x * req._y;
        break;
    case '/':
        if (0 == req._y)
            resp._code = 1;
        else
            resp._result = req._x / req._y;
        break;
    case '%':
        if (0 == req._y)
            resp._code = 2;
        else
            resp._result = req._x % req._y;
        break;
    default:
        resp._code = 3;
        break;
    }
    return resp;
}

void NetCal(Connection *conn, std::string &request)
{
    logMessage(DEBUG, "NetCal been called, get request: %s", request.c_str());
    Request req; // 1. 反序列化，1 + 1    2 + 3
    if(!req.Deserialized(request)) 
        return;

    Response resp = calculator(req); // 2. 业务处理

    std::string sendstr = resp.Serialize(); // 3. 序列化,构建应答
    sendstr = Encode(sendstr);

    conn->_outbuffer += sendstr; // 4. 交给服务器conn

    // 5. 想办法，让底层的TcpServer开始发送 -> 需要有完整的发送逻辑
    // 触发发送的动作，一旦开启EPOLLOUT，epoll会自动立马触发一次发送事件就绪，如果后续保持发送的开启，epoll会一直发送
    conn->_tsvr->EnableReadWrite(conn, true, true); // 写完EnableReadWrite才发现回指指针的作用
}

int main()
{
    std::unique_ptr<TcpServer> svr(new TcpServer());
    svr->Dispather(NetCal);

    return 0;
}